<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
        <style type="text/css">
            body, html{width: 100%;height: 100%;margin:0;font-family:"微软雅黑";}
            #allmap {width: 100%; height:500px; overflow: hidden;}
            #result {width:100%;font-size:12px;}
            dl,dt,dd,ul,li{
                margin:0;
                padding:0;
                list-style:none;
            }
        p{font-size:12px;}
        dt{
            font-size:14px;
            font-family:"微软雅黑";
            font-weight:bold;
            border-bottom:1px dotted #000;
            padding:5px 0 5px 5px;
            margin:5px 0;
        }
        dd{
            padding:5px 0 0 5px;
        }
        li{
            line-height:28px;
        }
        </style>
        <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=a5Sb4WiPKDN8ZfixSka8SDGX"></script>
        <!--加载鼠标绘制工具-->
        <script type="text/javascript" src="http://api.map.baidu.com/library/DrawingManager/1.4/src/DrawingManager_min.js"></script>
        <script type="text/javascript" src="http://api.map.baidu.com/library/GeoUtils/1.2/src/GeoUtils_min.js"></script>
        <link rel="stylesheet" href="http://api.map.baidu.com/library/DrawingManager/1.4/src/DrawingManager_min.css" />
        <!--加载检索信息窗口-->
        <script type="text/javascript" src="http://api.map.baidu.com/library/SearchInfoWindow/1.4/src/SearchInfoWindow_min.js"></script>
        <link rel="stylesheet" href="http://api.map.baidu.com/library/SearchInfoWindow/1.4/src/SearchInfoWindow_min.css" />
        <title>鼠标绘制工具</title>
    </head>
    <body>
        <div id="allmap" style="overflow:hidden;zoom:1;position:relative;">
            <div id="l-map" style="height:100%;-webkit-transition: all 0.5s ease-in-out;transition: all 0.5s ease-in-out;"></div>
        </div>
        <div id="paireOpaDiv">
            <table id="unPairedBizDatasTable" style="width:48%;float:left;" border=1></table>
            <table id="pairedBizDatasTable" style="width:48%;float:left;" border=1></table>
        </div>
        <div style="clear:both;"></div>
        <div id="result">
            <!--<input type="button" value="获取绘制的覆盖物个数" onclick="alert(overlays.length)"/>
             <input type="button" value="清除所有覆盖物" onclick="clearAll()"/>
             <input type="button" value="批量地址解析" onclick="bdGEO()" /><br />-->
        </div>
        <script type="text/javascript">
            var map;
            var bizDatas = new Array();
            var bizDatasMap = {};
            var drawingManager;
            var overlays = [];
            var unPairedBizDatas = [];
            var pairedBizDatas = [];
            var paireOpaManager = {
                tempSelectedBizData:null
            };
            var demoUtil;
            window.onload=function(){
                demoUtil = DemoUtils.createNew();
                map = loadMap();
                drawingManager = loadDrawingManager();
                loadBizData();
            }
        
        //自定义数据对象
        function BizData() {
            var id;
            var addr;
            var lng;
            var lat;
        }
        var styleOptions = {
            strokeColor:"red",    //边线颜色。
            //fillColor:"red",      //填充颜色。当参数为空时，圆形将没有填充效果。
            strokeWeight: 3,       //边线的宽度，以像素为单位。
            strokeOpacity: 0.8,	   //边线透明度，取值范围0 - 1。
            fillOpacity: 0.6,      //填充的透明度，取值范围0 - 1。
            strokeStyle: 'dashed' //边线的样式，solid或dashed。
        }
        function loadMap() {
            var map = new BMap.Map("l-map");
            map.centerAndZoom(new BMap.Point(117.269945,31.86713), 13);
            map.enableScrollWheelZoom(true);
            return map;
        }
        function loadBizData() {
            demoUtil.bdGEO();
            
        }
        
        
        function loadDrawingManager() {
            //实例化鼠标绘制工具
            var drawingManager = new BMapLib.DrawingManager(map, {
                                                            isOpen: true, //是否开启绘制模式
                                                            enableDrawingTool: true, //是否显示工具栏
                                                            drawingToolOptions: {
                                                            anchor: BMAP_ANCHOR_TOP_RIGHT, //位置
                                                            offset: new BMap.Size(5, 5), //偏离值
                                                            drawingModes : [
                                                                            //BMAP_DRAWING_MARKER,
                                                                            //BMAP_DRAWING_CIRCLE,
                                                                            //BMAP_DRAWING_POLYLINE,
                                                                            //BMAP_DRAWING_POLYGON,
                                                                            BMAP_DRAWING_RECTANGLE
                                                                            ]
                                                            },
                                                            //circleOptions: styleOptions, //圆的样式
                                                            //polylineOptions: styleOptions, //线的样式
                                                            //polygonOptions: styleOptions, //多边形的样式
                                                            rectangleOptions: styleOptions //矩形的样式
                                                            });
                                                            drawingManager.setDrawingMode(BMAP_DRAWING_RECTANGLE);
                                                            //添加鼠标绘制工具监听事件，用于获取绘制结果
                                                            drawingManager.addEventListener('overlaycomplete', onDrawComplete);
                                                            return drawingManager;
        }
        
        var onDrawComplete = function(e){
            for(var i = 0; i < overlays.length; i++){
                map.removeOverlay(overlays[i]);
            }
            overlays.length = 0
            
            overlays.push(e.overlay);
            
            DrawCompleteBizCallback(e.overlay.W);
        };
        
        function DrawCompleteBizCallback(W) {
            var pts = W;
            var ply = new BMap.Polygon(pts);
            
            
            var selectedBizDatas = new Array();
            for(var i=0; i<bizDatas.length; i++) {
                var pt =new BMap.Point(bizDatas[i].lng, bizDatas[i].lat);
                
                var result = BMapLib.GeoUtils.isPointInPolygon(pt, ply);
                if(result == true){
                    selectedBizDatas.push(bizDatas[i]);
                }
            }
            var tempstr = "";
            tempstr += "-------- "+new Date().Format("yyyy-MM-dd HH:mm:ss")+" 选择结果 --------</br>";
            if(selectedBizDatas.length==0){
                tempstr += "没有选中点<br/>";
            } else {
                for(var i=0; i<selectedBizDatas.length; i++) {
                    var temp =selectedBizDatas[i];
                    tempstr +=  temp.id + "、" + temp.addr + ":" + temp.lng + "," + temp.lat + "</br>";
                }
                loadPaireOpaModule(selectedBizDatas);
            }
            demoUtil.displayToResultDiv(tempstr);
            
            
        }
        
        function loadPaireOpaModule(selectedBizDatas) {
            var currentUnpairedBizDatas = [];
            var currentPairedBizDatas = [];
            for(var i=0; i<selectedBizDatas.length; i++) {
                //if selectedBizDatas[i] not in UnpairedBizDatas, add to currentUnpairedBizDatas
                if(unPairedBizDatas.contain(selectedBizDatas[i].id)) {
                    currentUnpairedBizDatas.push(selectedBizDatas[i].id);
                }
                else {
                    currentPairedBizDatas.push(selectedBizDatas[i].id);
                }
            }
            
            var unPaireTableDom = document.getElementById("unPairedBizDatasTable");
            deleteAllTr(unPaireTableDom.childNodes);
            if(null == unPaireTableDom.caption) {unPaireTableDom.createCaption();unPaireTableDom.appendChild(initTr("th",[" ","交接单号","拖送地址"]));}
            unPaireTableDom.caption.innerHTML=new Date().Format("yyyy-MM-dd HH:mm:ss")+" 选中区域中未拼单的数据";
            
            var paireTableDom = document.getElementById("pairedBizDatasTable");
            deleteAllTr(paireTableDom.childNodes);
            if(null == paireTableDom.caption) paireTableDom.createCaption();
            paireTableDom.caption.innerHTML=new Date().Format("yyyy-MM-dd HH:mm:ss")+" 选中区域中已拼单的数据";
            
            
            
            for(var i=0; i<currentUnpairedBizDatas.length; i++) {
                unPaireTableDom.appendChild(initTr("td",[{type:'input', attrs:[{key:'type',value:'checkbox'}]},bizDatasMap[currentUnpairedBizDatas[i]].id,bizDatasMap[currentUnpairedBizDatas[i]].addr]));
            }
            
            
            function deleteAllTr(trs) {
                for(var i=0; i<trs.length; i++) {
                    if(trs[i].nodeName == "CAPTION") continue;
                    if(trs[i].firstChild.nodeName == "TH") continue;
                    var tr = trs[i];
                    tr.parentNode.removeChild(tr);
                }
            }
            
            //tdType = td/th
            function initTr(tdType, tdValueArray) {
                var tr=document.createElement("tr");
                for(var i=0; i<tdValueArray.length; i++) {
                    var td=document.createElement(tdType);
                    var tdValue =tdValueArray[i];
                    if(typeof(tdValue)=="string") {
                        td.appendChild(document.createTextNode(tdValue));
                    } else {
                        var domObj = document.createElement(tdValue.type);
                        for(var y=0; y<tdValue.attrs.length; y++){
                            domObj[tdValue.attrs[y].key] = tdValue.attrs[y].value;
                        }
                        td.appendChild(domObj);
                        
                        if(domObj.nodeName=="INPUT" && domObj.type=="checkbox") {
                            domObj.onclick = onPaireCheckboxChecked;
                        }
                    }
                    tr.appendChild(td);
                }
                return tr;
            }
        }
        
        var onPaireCheckboxChecked = function() {
            //checked or not
            //paireOpaManager.tempSelectedBizData == null ?
            if(paireOpaManager.tempSelectedBizData == null) {
                //todo
            }
        }
        
        var  DemoUtils =  {
            createNew : function(){
                var util = {};
                util.index =  0;
                util.myGeo = new BMap.Geocoder();
                util.adds = [
                             "包河区金寨路1号（金寨路与望江西路交叉口）",
                             "庐阳区凤台路209号（凤台路与蒙城北路交叉口）",
                             "蜀山区金寨路217号(近安医附院公交车站)",
                             "蜀山区梅山路10号(近安徽饭店) ",
                             "蜀山区 长丰南路159号铜锣湾广场312室",
                             "合肥市寿春路93号钱柜星乐町KTV（逍遥津公园对面）",
                             "庐阳区长江中路177号",
                             "新站区胜利路89"
                             ];
                             util.generateBizId = function() {
                                 return "E"+Math.round(100000000*Math.random());
                             };
                             util.bdGEO = function(){
                                 var add = util.adds[util.index];
                                 util.geocodeSearch(add);
                                 util.index++;
                             };
                             
                             util.geocodeSearch = function (add){
                                 if(util.index < util.adds.length){
                                     setTimeout(util.bdGEO,400);
                                 }
                                 util.myGeo.getPoint(add, function(point){
                                                     if (point) {
                                                     util.displayToResultDiv(util.index + "、" + add + ":" + point.lng + "," + point.lat + "</br>");
                                                     
                                                     var bizDataObj = new BizData();
                                                     bizDataObj.id = util.generateBizId();
                                                     bizDataObj.addr = add;
                                                     bizDataObj.lng = point.lng;
                                                     bizDataObj.lat = point.lat;
                                                     bizDatas.push(bizDataObj);
                                                     unPairedBizDatas.push(bizDataObj.id);
                                                     bizDatasMap[bizDataObj.id] = bizDataObj;
                                                     
                                                     var address = new BMap.Point(point.lng, point.lat);
                                                     util.addMarker(address,new BMap.Label("",//index+":"+add,
                                                                                           {offset:new BMap.Size(20,-10)}));
                                                     }
                                                     }, "合肥市");
                             };
                             
                             util.displayToResultDiv = function(str) {
                                 var currentStr =document.getElementById("result").innerHTML;
                                 document.getElementById("result").innerHTML = str;
                                 document.getElementById("result").innerHTML+="<br/>"+currentStr;
                             };
                             util.addMarker =function(point,label){
                                 var marker = new BMap.Marker(point);
                                 map.addOverlay(marker);
                                 marker.setLabel(label);
                             }
                             return util;
            }
        }
        
        // 对Date的扩展，将 Date 转化为指定格式的String
        // 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，
        // 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
        // 例子：
        // (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
        // (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18
        Date.prototype.Format = function(fmt)
        { //author: meizz
            var o = {
                "M+" : this.getMonth()+1,                 //月份
                "d+" : this.getDate(),                    //日
                "H+" : this.getHours(),                   //小时
                "m+" : this.getMinutes(),                 //分
                "s+" : this.getSeconds(),                 //秒
                "q+" : Math.floor((this.getMonth()+3)/3), //季度
                "S"  : this.getMilliseconds()             //毫秒
            };
            if(/(y+)/.test(fmt))
            fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
            for(var k in o)
            if(new RegExp("("+ k +")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
            return fmt;
        }
        
        Array.prototype.contain = function(item){
            var flag =false;
            for(index in this){
                flag = (item==this[index])?true:false;
                if(flag)break;
            }
            return flag;
        }
        
        
            </script>
    </body>
</html>

